package com.guodexian.xiaomi.tx;

import com.guodexian.xiaomi.util.DbUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sql2o.Connection;
import org.sql2o.Sql2o;

/**
 * 类说明：  <br>
 *
 * @author 南阳德刚<br>
 * 2024-12-30 14:00<br>
 * @since 1.0 <br>
 * 培养IT高薪技术人才的摇篮---北京学佳澳。<br>
 * 点击<a href="http://www.xuejiaao.com/images/qrcode.jpg">学佳澳教育</a>关注公共号,有惊喜(⊙o⊙)<br>
 */
public class TransactionManager {
    private static final Logger logger = LoggerFactory.getLogger(TransactionManager.class);
    private static final ThreadLocal<Connection> LOCAL = new ThreadLocal<>();

    public static void beginTransaction() {
        Sql2o sql2o = DbUtil.getSql2o();
        LOCAL.set(sql2o.beginTransaction());
        logger.debug("事务启动");
    }
    public static void commitTransaction() {
        logger.debug("提交事务");
        Connection connection = LOCAL.get();
        if (connection != null) {
            connection.commit();
            LOCAL.remove();
        }
    }
    public static void rollbackTransaction() {
        logger.debug("回滚事务");
        Connection connection = LOCAL.get();
        if (connection != null) {
            connection.rollback();
            LOCAL.remove();
        }
    }
    public static Connection getConnection() {
        Connection connection = LOCAL.get();
        if (connection == null) {
            connection = DbUtil.getSql2o().open();
            LOCAL.set(connection);
        }
        return LOCAL.get();
    }
}